package com.hg.onlineshop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hg.onlineshop.config.AlipayConfig;
import com.hg.onlineshop.entity.*;
import com.hg.onlineshop.mapper.CartMapper;
import com.hg.onlineshop.mapper.ProductMapper;
import com.hg.onlineshop.service.IOrderItemService;
import com.hg.onlineshop.service.IOrderService;
import com.hg.onlineshop.utils.BusinessUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderContorller {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;

    @PostMapping("/pay")
    @ResponseBody
    public String payForOrder(@RequestBody Order order) {
        Integer id = order.getId();
        if (id == null) {
            return "E";
        }
        boolean flag = orderService.update(Wrappers.<Order>lambdaUpdate().eq(Order::getId, id).set(Order::getPayStatus, "已付款").set(Order::getOrderStatus, "未发货"));
        if (flag) {
            return "S";
        }
        return "E";
    }

    @GetMapping("/aliPay")
    public void aliPayForOrder(Order order, HttpServletResponse httpResponse) throws IOException {
        String price = "88.88";
        String id = order.getId().toString();
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, AlipayConfig.format, AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type); // 获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);// 在公共参数中设置回跳和通知地址
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(id);
        model.setTotalAmount("22.00");
        model.setSubject("xx");
        model.setProductCode("QUICK_MSECURITY_PAY");
        model.setTimeExpire("2m");
        alipayRequest.setBizModel(model);
//        alipayRequest.setBizContent("{" + "\"out_trade_no\":\"" + id
//                + "\"," + "\"product_code\":\"QUICK_MSECURITY_PAY\"," + "\"total_amount\":\""
//                + price + "\"," + "\"subject\":\"用户订单\","
//                + "\"body\":\"\","
//                + "\"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
//                + "\"extend_params\":{" + "\"sys_service_provider_id\":\"2016093000628009\"" + "}" + "}");// 填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @GetMapping("/list/{memberId}")
    @ResponseBody
    public List<Order> findOrdersByMemberId(@PathVariable("memberId") Integer memberId) {
        List<Order> orders = null;
        if (memberId == null) {
            return orders;
        }
        orders = orderService.list(Wrappers.<Order>lambdaQuery().eq(Order::getMemberId, memberId));
        return orders;
    }

    @PostMapping("/save/{addressId}")
    @ResponseBody
    @Transactional
    public String saveOrder(@RequestBody List<OrderItem> orderItems,@PathVariable("addressId")Integer addressId, HttpSession session) {
        if (orderItems != null && orderItems.size() > 0) {
            // 生成订单号
            String orderCode = BusinessUtils.getOrderCode();
            // 获取用户信息
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return "E";
            }
            Integer memberId = user.getId();
            BigDecimal sumAmount = new BigDecimal(0);
            // 当前时间
            Date curDate = new Date();
            List<Product> products = new ArrayList<>();
            for (OrderItem item : orderItems) {
                item.setOrderCode(orderCode);
                item.setSaveTime(curDate);
                Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getId, item.getProductId()));
                if (product != null) {
                    int num = item.getNum();
                    int inventory = product.getInventory();
                    if (inventory >= num) {
                        product.setInventory(product.getInventory() - num);
                        products.add(product);
                        sumAmount = sumAmount.add(new BigDecimal(product.getPrice() * num));
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return "P";
                    }
                }
            }
            orderItemService.saveBatch(orderItems);
            Order order = new Order();
            order.setMemberId(memberId);
            order.setOrderCode(orderCode);
            order.setSaveTime(curDate);
            order.setAddressId(addressId);
            order.setPayStatus("待付款");
            order.setTotal(sumAmount);
            orderService.save(order);
            // 更新商品库存
            for (Product product : products) {
                productMapper.updateById(product);
            }
            // 清空购物车列表
            cartMapper.delete(Wrappers.<Cart>lambdaUpdate().eq(Cart::getMemberId, memberId));
            return "S";
        }
        return "E";
    }
}
